package com.tripreset.todo

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase

@Database(entities = [TodoEntity::class], version = 2)
abstract class TodoAppDatabase : RoomDatabase() {

    abstract fun getTodoDao(): TodoDao

    companion object {

        // For Singleton instantiation
        @Volatile
        var instance: TodoAppDatabase? = null

        fun init(context: Context): TodoAppDatabase {
            return instance ?: synchronized(this) {
                instance ?: buildDatabase(context).also { instance = it }
            }
        }

        // Create and pre-populate the database. See this article for more details:
        // https://medium.com/google-developers/7-pro-tips-for-room-fbadea4bfbd1#4785
        private fun buildDatabase(context: Context): TodoAppDatabase {
            return Room.databaseBuilder(context, TodoAppDatabase::class.java, "todo-db")
                .addMigrations(MIGRATION_1_2)
                .build()
        }

        private val MIGRATION_1_2 = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE t_todo ADD COLUMN t_title TEXT NOT NULL DEFAULT ''")
                database.execSQL("ALTER TABLE t_todo ADD COLUMN t_content TEXT NOT NULL DEFAULT ''")
            }
        }
    }

}